<template>
  <div class="dashboard-container">
    <el-card 
      class="box-card" 
      v-loading="loading"
    >
      <!-- 表单输入框 -->
      <el-form 
        ref="form" 
        :model="form" 
        label-width="80px" 
        :inline="true"
      >
        <el-form-item label="标签名称">
          <el-input 
            v-model="form.tags" 
            placeholder="请输入"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="城市">
          <el-select 
            v-model="form.province" 
            placeholder="请选择"
          >
            <el-option
              :label="province"
              :value="province"
              v-for="(province, i) in getProvincesList"
              :key="i"
            >
            </el-option>
          </el-select>
        </el-form-item>
         <el-form-item label="地区">
          <el-select 
            v-model="form.city" 
            placeholder="请选择"
          >
            <el-option
              :label="city"
              :value="city"
              v-for="(city, i) in getCityList"
              :key="i"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业简称">
          <el-input v-model="form.shortName"></el-input>
        </el-form-item>
           <el-form-item label="状态">
          <el-select 
            v-model="form.state" 
            placeholder="请选择"
          >
            <el-option 
              label="启用" 
              value="1"
            >
            </el-option>
            <el-option 
              label="禁用" 
              value="0"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 搜索/清除按钮 -->
        <el-button
          class="remove-btn"
          @click="onRemoveAll"
        >
          清除
        </el-button>
        <el-button
          type="primary"
          @click="onSearchCompanyList"
        >
          搜索
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-edit"
          class="addUser"
          @click="onAddCompanyList"
        >
          新增用户
        </el-button>
      </el-form>
      <!-- 新增/编辑 对话框 -->
      <el-dialog
        :title="ruleForm.shortName ? '编辑用户' : '创建用户'"
        :visible.sync="addVisible"
        width="400"
        :center="true"
        v-loading="loading"
      >
        <el-form 
          :model="ruleForm" 
          :rules="rules" 
          ref="ruleForm" 
          label-width="100px" 
          class="demo-ruleForm"
        >
          <el-form-item 
            label="企业名称" 
            prop="shortName"
          >
            <el-input v-model="ruleForm.shortName"></el-input>
          </el-form-item>
          <el-form-item 
            label="所属公司" 
            prop="company"
          >
            <el-input v-model="ruleForm.company"></el-input>
          </el-form-item>
          <div class="link">
            <a href="https://www.tianyancha.com ">https://www.tianyancha.com在此可查询所属公司全称及简称</a>
          </div>
          <el-form-item 
            label="城市地区" 
            prop="province" 
            :inline="true" 
            class="s"
          >
            <el-select 
              v-model="ruleForm.province" 
              placeholder="请选择"
            >
              <el-option
                :label="province"
                :value="province"
                v-for="(province, i) in getProvincesList"
                :key="i"
              ></el-option>
            </el-select>
            &nbsp;
            <el-select 
              v-model="ruleForm.city" 
              placeholder="请选择"
            >
              <el-option
                :label="city"
                :value="city"
                v-for="(city, i) in getCityList"
                :key="i"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item 
            label="企业标签" 
            prop="tags"
          >
            <el-input v-model="ruleForm.tags"></el-input>
          </el-form-item>
          <el-form-item 
            label="备注" 
            prop="remarks"
          >
            <el-input 
              type="textarea" 
              v-model="ruleForm.remarks"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <span 
          slot="footer" 
          class="dialog-footer"
        >
          <el-button @click="addVisible = false">取 消</el-button>
          <el-button 
            type="primary" 
            @click="addCompanyOk"
          >
            确 定
          </el-button>
        </span>
      </el-dialog>
      <!-- 提示 -->
      <el-alert
        :closable="false"
        :title="`共${companyList.counts}条纪录`"
        type="info"
        class="hint"
        show-icon>
      </el-alert>
      <!-- 表格 -->
      <my-table
        class="container"
        :table-props="{
          data: companyList.items,
          border: true
        }"
        :columns="[
          { label: '序号', prop: 'index', width: 180, align: 'center' },
          { label: '企业编号', prop: 'number', width: 180, align: 'center'},
          { label: '企业简称', prop: 'shortName', width: 180, align: 'center' },
          { label: '标签', prop: 'tags', width: 180, align: 'center' },
          { label: '创建者', prop: 'creatorID', width: 180, align: 'center' },
          { label: '创建日期', prop: 'addDate', sortable: true, align: 'center', width: 180 },
          { label: '备注', prop: 'remarks', align: 'center',width: 180},
          { label: '状态', prop: 'state', width: 180, width: 180, align: 'center'},
          { label: '操作', width: 180, align: 'center', slotName: 'handle', width: 300, fixed: 'right'},
        ]"

        :pagination-props="{
          layout: 'sizes, prev, pager, next, jumper',
          total: companyList.counts,
          currentPage: page,
          pageSize: pageSize,
          pageSizes: [10, 20, 30, 40],
        }"
        :pagination-events="{
          'current-change': onCurrentPageChange,
          'size-change': onPageSizeChange
        }"
      >
      <template v-slot:handle="scope" >
        <el-button 
          type="primary" 
          icon="el-icon-edit" 
          @click="onAddCompanyList(scope.row.id)" 
          circle
        >
        </el-button>
        <el-button 
          type="success" 
          icon="el-icon-check" 
          @click="onForbidden(scope.row)" 
          v-show="scope.row.state === '禁用'" 
          circle
        >
        </el-button>
        <el-button 
          type="warning" 
          icon="el-icon-close" 
          @click="onForbidden(scope.row)" 
          v-show="scope.row.state === '启用'" 
          circle
        >
        </el-button>
        <el-button type="danger" 
          icon="el-icon-delete" 
          @click="onRemove(scope.row.id)" 
          circle
        >
        </el-button>
      </template>
      </my-table>
    </el-card>
  </div>
</template>

<script>
let currentId = null
// let that = null
import * as citysApi from '../../api/hmmm/citys';
import * as companyApi from '../../api/hmmm/companys';
import { mapActions, mapState } from 'vuex'
export default {
  name: 'CompanysList',
  data () {
    return {
      loading: false,
      form: {
        tags: '',
        province: '',
        city: '',
        shortName: '',
        state: ''
      },
      ruleForm: {
        shortName: '',
        company: '',
        province: '',
        city: '',
        tags: '',
        remarks: '',
        isFamous: true,
      },
      page: 1,
      pageSize: 10,
      addVisible: false,
      editVisible: false,
      visible: false,
      rules: {
        shortName: [
          { required: true, message: '请输入企业名称', trigger: 'blur' },
        ],
        company: [
          { required: true, message: '请输入所属公司', trigger: 'blur' }
        ],
        province: [
          {required: true, message: '请选择城市', trigger: 'blur' }
        ],
        tags: [
          { required: true, message: '请输入企业标签', trigger: 'blur' }
        ],
        remarks: [
          { required: true, message: '请填写备注', trigger: 'blur' }
        ]
      },
    }
  },
  computed: {
    ...mapState('company', ['companyList', 'detailCompany']),
    // 获取城市列表
    getProvincesList() {
      return citysApi.provinces()
    },
    // 获取城市下边地区列表
    getCityList() {
      if(this.form.province !== '') {
        return citysApi.citys(this.form.province)
      }else{
        return citysApi.citys(this.ruleForm.province)
      }

    }
  },
  methods: {
    ...mapActions('company', ['updateCompanyList', 'updateDetailCompany']),
    // 点击下一页
    onCurrentPageChange(val) {
      this.page = val
      this.updateCompanyList({
        page: this.page,
        pagesize: this.pageSize,
      })

    },
    onPageSizeChange(val) {
      this.page = 1
      this.pageSize = val
      this.updateCompanyList({
        page: this.page,
        pagesize: this.pageSize,
      })
    },
    // 清除按钮
    onRemoveAll() {
      this.form = {
        name: '',
        provinces: '',
        city: '',
        management: '',
        state: ''
      }
    },
    // 搜索按钮
    onSearchCompanyList() {
      this.updateCompanyList({
        ...this.form,
        page: this.page,
        pagesize: this.pageSize
      })
    },
    // 新增/编辑企业
    async onAddCompanyList(id) {
      if(!isNaN(id)) {
        currentId = id
        await this.updateDetailCompany({id})
        this.addVisible = true
        this.ruleForm.shortName = this.detailCompany.data.shortName,
        this.ruleForm.company =  this.detailCompany.data.company,
        this.ruleForm.province = this.detailCompany.data.province,
        this.ruleForm.city = this.detailCompany.data.city,
        this.ruleForm.tags = this.detailCompany.data.tags,
        this.ruleForm.remarks = this.detailCompany.data.remarks,
        this.ruleForm.isFamous = this.detailCompany.data.isFamous === 1 ? true : false
      }else{
        currentId = null
        this.ruleForm.shortName = ''
        this.ruleForm.company =  '',
        this.ruleForm.province = '',
        this.ruleForm.city = '',
        this.ruleForm.tags = '',
        this.ruleForm.remarks = '',
        this.ruleForm.isFamous = ''
        // this.$refs.ruleForm.resetFields();
        this.addVisible = true
      }

    },
    // 点击确定新增/编辑按钮
    async addCompanyOk() {
      if (currentId) {
        await companyApi.updateCompany({
          id: currentId,
          ...this.ruleForm,
          addDate: this.detailCompany.data.addDate,
          creatorID: this.detailCompany.data.creatorID,
          number: this.detailCompany.data.number,
          state: this.detailCompany.data.state
        })
          .then(res => this.$message.success('操作成功'))
          .catch(err => this.$message.error('操作失败'))
      }else{
        await companyApi.addCompany({
        ...this.ruleForm,
         isFamous: true,

        })
          .then(res => this.$message.success('操作成功'))
          .catch(err => this.$message.error('操作失败'))
      }
      this.addVisible = false
      this.updateCompanyList({ page: this.page, pagesize: this.pageSize })
    },
    // 删除
    onRemove(id) {
      this.$confirm('此操作将永久删除该企业, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await companyApi.removeCompany({id})
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.updateCompanyList({ page: this.page, pagesize: this.pageSize })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
      },
    // 是否禁用
    onForbidden(scope) {
      this.$confirm(`此操作将${scope.state === '禁用' ? '启用' : '禁用'}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await companyApi.disabled({
          id: scope.id,
          state: scope.state === '禁用' ? 1 : 0
        })
        this.$message({
          type: 'success',
          message: `已成功${scope.state === '禁用' ? '启用' : '禁用'}`
        });
        this.updateCompanyList({ page: this.page, pagesize: this.pageSize })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: `已取消${scope.state === '禁用' ? '启用' : '禁用'}`
        });
      });
    },

  },
  async created () {
    this.loading = true
    // that = this
    await this.updateCompanyList({ page: this.page, pagesize: this.pageSize })
    this.loading = false
  }
}
</script>

<style lang="scss" scoped>

.dashboard-container {
  padding: 16px;

  .remove-btn {
    margin-left: 18px;
  }

  .icon {
    font-size: 24px;

  }
  .el-icon-circle-close,
  .el-icon-circle-check {
    margin: 0 24px;
  }

  .addUser {
    float: right;
    background-color: #7ec050;
    border: none;
  }

  .link {
    display: flex;
    justify-content: center;
    margin-bottom: 16px;
  }
  .hint {
    margin-bottom: 10px;
  }
}
</style>
